package models

import "github.com/go-xorm/xorm"

type ControlCenter struct {
	Id        int `json:"id" xorm:"smallint pk autoincr"`
	Xid       int `json:"xid" xorm:"int"`
	Type      int `json:"type" xorm:"int"`
	Tid       int `json:"tid" xorm:"int"`
	BaseModel `json:"-" xorm:"-"`
}

// 新增
func (center *ControlCenter) Create() (insertId int, err error) {
	_, err = Db.Insert(center)
	if err == nil {
		insertId = center.Id
	}

	return
}

func (center *ControlCenter) UpdateBean(id int) (int64, error) {
	return Db.ID(id).Cols("xid,type,tid").Update(center)
}

// 更新
func (center *ControlCenter) Update(id int, data CommonMap) (int64, error) {
	return Db.Table(center).ID(id).Update(data)
}

// 删除
func (center *ControlCenter) Delete(id int) (int64, error) {
	return Db.Id(id).Delete(new(ControlCenter))
}

func (center *ControlCenter) Find(id int) error {
	_, err := Db.Id(id).Get(center)

	return err
}

func (center *ControlCenter) Detail(id int) (ControlCenter, error) {
	t := ControlCenter{}
	_, err := Db.Id(id).Get(&t)

	return t, err
}

func (center *ControlCenter) List(params CommonMap) ([]ControlCenter, error) {
	center.parsePageAndPageSize(params)
	list := make([]ControlCenter, 0)
	session := Db.Desc("id")
	center.parseWhere(session, params)
	err := session.Limit(center.PageSize, center.pageLimitOffset()).Find(&list)

	return list, err
}

// 解析where
func (center *ControlCenter) parseWhere(session *xorm.Session, params CommonMap) {
	if len(params) == 0 {
		return
	}
	id, ok := params["Xid"]
	if ok && id.(int) > 0 {
		session.And("xid = ?", id)
	}
	name, ok := params["Name"]
	if ok && name.(string) != "" {
		session.And("name = ?", name)
	}
}

func (center *ControlCenter) CenterTargetExists(xid, Type, tid int) (bool, error) {
	//if id == 0 {
	//	count, err := Db.Where("name = ?", name).Count(host)
	//	return count > 0, err
	//}

	count, err := Db.Where("xid = ? AND type = ? AND tid = ?", xid, Type, tid).Count(center)
	return count > 0, err
}
